<script setup lang="ts">
import {zhCn} from 'element-plus/es/locale/index'
import Loading from '@/views/Loading.vue'
import NoNetwork from '@/views/NoNetwork.vue'
import Header from '@/components/header/Header.vue'
import {onMounted, type Ref, ref} from 'vue'
import {getUserInfo} from '@/network/api/user.ts'
import {cleanLocalStorageToken, cleanUserInfo, getLocalStorageToken, userInfo} from '@/stores/user.ts'
import {ElMessageBox, ElNotification} from 'element-plus'
import {useRouter} from 'vue-router'
import axios from 'axios'
import {apiUrl} from '@/stores/constant.ts'

const router = useRouter()
const hasNetwork: Ref<'loading' | 'noNetwork' | 'hasNetwork'> = ref('loading')
const show = ref(false)

onMounted(() => {
  axios.get(apiUrl).then(() => {
    hasNetwork.value = 'hasNetwork'
  }).catch(() => {
    hasNetwork.value = 'noNetwork'
  })
  let token = getLocalStorageToken()
  if (token) {
    userInfo.value.token = token
    getUserInfo().then(res => {
      if (res.ok) {
        userInfo.value = res.data
        userInfo.value.token = token
        show.value = true
        ElNotification({
          title: '自动登录成功',
          type: 'success'
        })
      }
      if (res.code === 1001) {
        show.value = true
        ElMessageBox.confirm('请重新登录', '自动登录失败', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          router.push('/user/login')
        }).catch(() => {
          ElNotification({
            title: '取消登录',
            type: 'error'
          })
        })
        cleanLocalStorageToken()
        cleanUserInfo()
      }
    })
  } else {
    show.value = true
  }
})
</script>

<template>
  <!-- ElementPlus国际化：中文 -->
  <el-config-provider
      :locale="zhCn"
  >
    <Loading v-if="hasNetwork==='loading'"/>
    <NoNetwork v-if="hasNetwork==='noNetwork'"/>
    <template v-if="hasNetwork==='hasNetwork'&&show">
      <Header/>
      <div>
        <router-view/>
      </div>
    </template>
  </el-config-provider>
</template>

<style scoped>

</style>
